package com.yf1706.controller;

import java.io.IOException;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.beans.factory.annotation.Autowired;

import com.alibaba.fastjson.JSON;
import com.yf1706.bean.Emp;
import com.yf1706.bean.User;
import com.yf1706.service.EmpService;
/**
 * 用于存放所有Controller的共用方法
 *
 */
public class BaseController {
	
	@Autowired
	private EmpService empService;

	/**
	 * 将对象抓换成JSON字符串，并相应回前台
	 * @param object
	 * @param response
	 */
	public void writeJson(Object object,HttpServletResponse response) {
		response.setContentType("text/html;charset=UTF-8");
		try {
			response.getWriter().print(JSON.toJSONString(object));
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
	
	/**
	 * 去除字符串首尾字符
	 * @param source 源字符串
	 * @return
	 */
	public String removeFirstAndLastChar(String source) {
		source = source.substring(1);
		source = source.substring(0,source.length()-1);
		return source;
	}
	
	/**
	 * 返回当前登录的用户
	 * @param response
	 */
	public User getSessionUser(HttpServletRequest request) {
		
		return (User) request.getSession().getAttribute("user");
	}
	
	/**
	 * 根据员工编号获取员工对象(基本表)
	 * @param empId
	 * @return
	 */
	public Emp getEmpByEid(int empId) {
		return empService.queryById(empId);
	}
	
	/**
	 * 返回当前登录的用户的姓名
	 * @param response
	 */
	public String getSessionUserName(HttpServletRequest request) {
		User user = (User) request.getSession().getAttribute("user");
		Emp emp = getEmpByEid(user.getEmp().getEmpId());
		return emp.getEmpName();
	}
	
}
